package com.clothing.customization.controller;

import com.clothing.customization.dto.ApiResult;
import com.clothing.customization.dto.AuthResponse;
import com.clothing.customization.dto.LoginRequest;
import com.clothing.customization.dto.RegisterRequest;
import com.clothing.customization.entity.User;
import com.clothing.customization.service.UserService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {
    
    private final UserService userService;
    
    /**
     * 用户登录
     * @param request 登录请求
     * @return 登录结果
     */
    @PostMapping("/login")
    public ResponseEntity<ApiResult<AuthResponse>> login(@Valid @RequestBody LoginRequest request) {
        try {
            AuthResponse response = userService.login(request);
            return ResponseEntity.ok(ApiResult.success("登录成功", response));
        } catch (BadCredentialsException e) {
            return ResponseEntity.ok(ApiResult.error(401, e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResult.error("登录失败：" + e.getMessage()));
        }
    }
    
    /**
     * 用户注册（仅限普通用户）
     * @param request 注册请求
     * @return 注册结果
     */
    @PostMapping("/register")
    public ResponseEntity<ApiResult<User>> register(@Valid @RequestBody RegisterRequest request) {
        try {
            User user = userService.register(request);
            return ResponseEntity.ok(ApiResult.success("注册成功", user));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.ok(ApiResult.error(400, e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResult.error("注册失败：" + e.getMessage()));
        }
    }
    
    /**
     * 检查用户名是否可用
     * @param username 用户名
     * @return 检查结果
     */
    @GetMapping("/check-username")
    public ResponseEntity<ApiResult<Boolean>> checkUsername(@RequestParam String username) {
        boolean exists = userService.isUsernameExists(username);
        return ResponseEntity.ok(ApiResult.success(!exists));
    }
} 